<?php

namespace App\Libraries;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;

class Claude
{
    public function run($messages)
    {
        try {
            $headers = [
                'Content-Type' => 'application/json',
                'anthropic-version' => env('ANTHROPIC_API_VERSION'),
                'x-api-key' => env('ANTHROPIC_API_KEY')
            ];
            // 请求参数
            $body = json_encode([
                'model' => 'claude-3-5-sonnet-20241022',
                'max_tokens' => 8192,
                'temperature' => 0.7,
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $messages
                    ]
                ]
            ]);

            $client = new Client([
                'timeout'  => 120, // 设置请求超时时间为10秒
                'connect_timeout' => 10, // 设置连接超时时间为5秒
            ]);
            $uri = 'https://api.anthropic.com/v1/messages';
            $response = $client->post($uri, [
                'headers' => $headers,
                'body' => $body
            ]);
            if ($response->getStatusCode() != 200) {
                return false;
            }
            return json_decode($response->getBody()->getContents(), true);
        } catch (RequestException $e) {
            dd($e->getMessage());
        } catch (ConnectException $e) {
            dd($e->getMessage());
        }
    }

    public function count_tokens($messages)
    {
        try {
            $headers = [
                'Content-Type' => 'application/json',
                'anthropic-version' => env('ANTHROPIC_API_VERSION'),
                'anthropic-beta' => 'token-counting-2024-11-01',
                'x-api-key' => env('ANTHROPIC_API_KEY')
            ];
            // 请求参数
            $body = json_encode([
                'model' => 'claude-3-5-sonnet-20241022',
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $messages
                    ]
                ]
            ]);

            $client = new Client([
                'timeout'  => 120, // 设置请求超时时间为10秒
                'connect_timeout' => 5, // 设置连接超时时间为5秒
            ]);
            $uri = 'https://api.anthropic.com/v1/messages/count_tokens';
            $response = $client->post($uri, [
                'headers' => $headers,
                'body' => $body
            ]);
            if ($response->getStatusCode() != 200) {
                return false;
            }
            $result = json_decode($response->getBody()->getContents(), true);
            return $result;
        } catch (RequestException $e) {
            dd($e->getMessage());
        } catch (ConnectException $e) {
            dd($e->getMessage());
        }
    }
}
